package sms

import (
	"errors"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
	"github.com/astaxie/beego/logs"
	"github.com/axgle/mahonia"
	"math/rand"
	"smart_home/api/utils"
	"strconv"
	"time"
)

func init() {
	//以时间作为初始化种子
	rand.Seed(time.Now().UnixNano())
}

// 获取设置验证码
func SetCode(mobile int64) (string, error) {
	code := fmt.Sprintf("%04v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(10000))
	if err := Send(mobile, code); err != nil {
		logs.Error("send sms error:", err)
		return "", err
	}

	// 保存验证码
	err := utils.Cache.Put(fmt.Sprintf("sms:%d", mobile), code, 60*10*time.Second)
	if err != nil {
		logs.Error("cache put sms code error:", err)
		return "", err
	}

	return code, nil
}

func ValidateCode(mobile int64, vcode string) error {
	// 取出验证码
	code := fmt.Sprintf("%s", utils.Cache.Get(fmt.Sprintf("sms:%d", mobile)))
	if code != vcode {
		err := errors.New("验证码错误")
		return err
	}
	return nil
}

func Send(mobile int64, content string) error {
	smsUrl := fmt.Sprintf("%s/sdk2/BatchSend2.aspx", beego.AppConfig.DefaultString("sms_host", "https://sdk2.028lk.com"))

	enc := mahonia.NewEncoder("gbk")
	body, err := httplib.Post(smsUrl).
		Param("CorpID", beego.AppConfig.DefaultString("sms_account", "")).
		Param("Pwd", beego.AppConfig.DefaultString("sms_password", "")).
		Param("Mobile", fmt.Sprintf("%d", mobile)).
		Param("Content", enc.ConvertString(fmt.Sprintf("验证码：%s（10分钟内有效），请及时完成验证。【中华商务网】", content))).
		String()
	if err != nil {
		return err
	}

	res, err := strconv.Atoi(body)
	if err != nil {
		return err
	}
	if res < 0 {
		return errors.New("信息发送失败")
	}
	return nil
}
